package com.mobimap.nhom9.gui;

import java.util.ArrayList;

import android.graphics.Point;
import android.util.Log;

public class ConvertToPixel {
	private MyPoint TOA_DO_THUC_1 = new MyPoint(10.762247f, 106.682825f);
	private MyPoint TOA_DO_PIXEL_1 = new MyPoint(2165f, 1384f);
	private MyPoint TOA_DO_THUC_2 = new MyPoint(10.771298f, 106.673123f);
	private MyPoint TOA_DO_PIXEL_2 = new MyPoint(1964f, 1185f);
	private ArrayList<MyPoint> listMocToaDoThuc = new ArrayList<MyPoint>();
	private ArrayList<MyPoint> listMocToaDoPixel = new ArrayList<MyPoint>();
	public ConvertToPixel() {
		// TODO Auto-generated constructor stub
		listMocToaDoThuc.add(TOA_DO_THUC_1);
        listMocToaDoPixel.add(TOA_DO_PIXEL_1);

        listMocToaDoThuc.add(TOA_DO_THUC_2);            
        listMocToaDoPixel.add(TOA_DO_PIXEL_2);

        //dai truyen hinh
        listMocToaDoThuc.add(new MyPoint(10.7861f, 106.7022f));
        listMocToaDoPixel.add(new MyPoint(6 * 256 + 60, 7 * 256 + 80f));


	}

	private float KhoanhCach(MyPoint p1, MyPoint p2)// tinh khoang cach giua 2 diem
	{
		return (float) Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y)
				* (p1.y - p2.y));
	}

	 public MyPoint LayTiLePixelTrenToaDo() {
		 
		 float deltaToaDoThucX = TOA_DO_THUC_1.x - TOA_DO_THUC_2.x;
         float deltaToaDoThucY = TOA_DO_THUC_1.y - TOA_DO_THUC_2.y;

         float deltaToaDoPixelX = TOA_DO_PIXEL_1.x - TOA_DO_PIXEL_2.x;
         float deltaToaDoPixelY = TOA_DO_PIXEL_1.y - TOA_DO_PIXEL_2.y;

         return new MyPoint(deltaToaDoPixelY / deltaToaDoThucY, deltaToaDoPixelX / deltaToaDoThucX);
		
	}

	public Point Convert(MyPoint toaDoThuc3)
    {           
		MyPoint p = LayTiLePixelTrenToaDo();
		Log.i("MyPoint",p.toString());
        //kiem tra xem diem nao moc nao gan diem dang xet nhat
		float[] listKhoangCach = new float[listMocToaDoThuc.size()];
		for(int i=0; i<listMocToaDoThuc.size(); i++)
        {
            listKhoangCach[i] =
           		 KhoanhCach(listMocToaDoThuc.get(i),toaDoThuc3); // list khoang cach tu diem can tim den cac diem moc
        }

		int minIndex = 0; // index cua diem moc gan nhat
        for(int i=1; i<listKhoangCach.length; i++)
            if(listKhoangCach[i] < listKhoangCach[minIndex])
                minIndex = i;
        
        float deltaToaDoThuc3vsMocx = toaDoThuc3.x - listMocToaDoThuc.get(minIndex).x; // lay min
        float deltaToaDoThuc3vsMocy = toaDoThuc3.y - listMocToaDoThuc.get(minIndex).y; // lay min
        
        MyPoint mypoint =  new MyPoint(deltaToaDoThuc3vsMocy * p.x + listMocToaDoPixel.get(minIndex).y,
                         deltaToaDoThuc3vsMocx * p.y + listMocToaDoPixel.get(minIndex).x);
        
        return new Point((int)mypoint.x, (int)mypoint.y);

    }

	
}
